<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品编辑</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert
        title="提示：必须选择分类才能切换面板"
        center
        type="info"
        show-icon
        style="margin-bottom: 10px"
      >
      </el-alert>
      <el-steps :active="+active" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品照片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-tabs :tab-position="tabPosition" v-model="active" :before-leave="handlerLeave" @tab-click="handlerTabClick">
        <el-tab-pane label="基本信息" name="0">
          <el-form :model="editForm">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="editForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="editForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="editForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="editForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="editForm.goods_cat"
                :options="tableData"
                :props="{
                  expandTrigger: 'hover',
                  value: 'cat_id',
                  label: 'cat_name',
                }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="商品参数" name="1">
          <el-form label-position="top">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox
                      :label="item2"
                      border
                      v-for="(item2, index2) in item.attr_vals"
                      :key="index2"
                      >{{ item2 }}</el-checkbox
                    >
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="商品属性" name="2">
          <el-form>
            <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="商品图片" name="3">
          <el-upload
            class="upload-demo"
            action="http://shop.zhuox.net/api/private/v1/upload"
            :headers="headerObj"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>

        <el-tab-pane label="商品内容" name="4">
          <quill-editor v-model="editForm.goods_introduce" :options="{placeholder:'请输入产品介绍内容'}" />
          <el-button type="primary" @click="edit">修改商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      active: 0,
      tabPosition: "left",
      value: "",
      tableData: [],
      editForm:{
        goods_name: "",
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      headerObj:{
        Authorization:sessionStorage.getItem("token")
      },
      manyData:[],
      onlyData:[],
    };
  },
  methods: {
    // 分类列表
    async list() {
      const {
        data: { data, meta },
      } = await this.$http.get("categories");
      if (meta.status !== 200) return this.$message.error("获取分类列表失败");
      this.tableData = data;
    },
    async handleChange(){
      if(this.editForm.goods_cat.length!==3){
        this.editForm.goods_cat=[];
      }
    },
    handlerLeave(a,o){
      if(o==='0'&&this.editForm.goods_cat.length!==3){
        this.$message.warning("请先选择商品分类");
        return false;
      }
    },
    handleRemove(file){
      const i = this.editForm.pics.findIndex(item=>item.pic===file.response.data.tmp_path)
      this.editForm.pics.splice(i,1)
    },
    handleSuccess({meta,data:{tmp_path}}){
      if(meta.status!==200) return this.$message.error('上传图片失败')
      this.editForm.pics.push({pic:tmp_path})
    },
    // 获取原数据
    async oldlist(){
      const {data:{data,meta}} = await this.$http.get(`goods/${this.$route.params.id}`)
      this.editForm.goods_name=data.goods_name
      let cat = data.goods_cat.split(',')
      cat.forEach((item,index)=>{
        cat[index] = parseInt(item)
      })
      this.editForm.goods_cat=cat
      this.editForm.goods_price=data.goods_price
      this.editForm.goods_number=data.goods_number
      this.editForm.goods_weight=data.goods_weight
      this.editForm.goods_introduce=data.goods_introduce
      this.editForm.pics=data.pics
      this.editForm.attrs=data.attrs
    },
    async edit(){
      let newcat = JSON.parse(JSON.stringify(this.editForm));
      newcat.goods_cat = newcat.goods_cat.join(",");
        this.manyData.forEach(item=>{
          newcat.attrs.push({
                attr_id:item.attr_id,
                attr_value:item.attr_vals.join(" ")
            })
        })

        this.onlyData.forEach(item=>{
          newcat.attrs.push(
                {
                    attr_id:item.attr_id,
                    attr_value:item.attr_vals
                }
            )
        })

        const {data:{meta}} = await this.$http.put(`goods/${this.$route.params.id}`,newcat);
        if(meta.status !== 200) return this.$message.error('修改商品失败')
        this.$message.success('修改商品成功')
    },
    async handlerTabClick(){
      if(this.active==1){
        const {data:{data,meta}} = await this.$http.get(`categories/${this.cartId}/attributes`,{params: { sel: "many" }})
        if(meta.status!==200) return this.$message.error('请求商品参数失败')
        data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        });
        this.manyData = data;
      }
      else if(this.active==2){
        const {data:{data,meta}} = await this.$http.get(`categories/${this.cartId}/attributes`,{params: { sel: "only" }})
        if(meta.status!==200) return this.$message.error('请求商品属性失败')
        this.onlyData = data;
      }
    }
  },
  computed:{
    cartId(){
      return this.editForm.goods_cat[this.editForm.goods_cat.length-1]
    }
  },
  created() {
    this.list();
    this.oldlist()
  },
};
</script>